package servlets.chatting;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.moma.chatting.core.Message;
import com.moma.chatting.core.ChattingManager;
import com.moma.chatting.exception.UserExpiredException;

public class MessageRecv extends HttpServlet {
	private ChattingManager mgr = null;
	//private JsonGenerator jsonGenerator = null;
	private ObjectMapper objectMapper2 = null;
	
	@Override
	public void init(){
		mgr = ChattingManager.getInstance();
		mgr.initialize();
		
		objectMapper2 = new ObjectMapper();
//		try {
//            jsonGenerator = objectMapper.getFactory().createGenerator(System.out, JsonEncoding.UTF8);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }
	
	@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
		doPost(request, response);
	}
	
	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
		// http://messaging.com/messageRecv?id=abc&conversationId=1;
		PrintWriter out = response.getWriter();
		String userUniqueName = request.getParameter("id");
		String conversationIdText = request.getParameter("conversationId");
		int conversationId = 0;
		if (conversationIdText != null && conversationIdText != ""){
			conversationId = Integer.valueOf(conversationIdText);
		}
		
		String debugInfo = "aaa";
		Message[] msgArray = null;
		try {
			msgArray = mgr.recvMessage(userUniqueName, conversationId);
			debugInfo = objectMapper2.writeValueAsString(msgArray);
		} catch (UserExpiredException	 e) {
			// TODO Auto-generated catch block
			debugInfo = e.toString();
		}
		
		out.println(debugInfo);
	}
}
